package tech.mobi.child;

import java.util.ArrayList;
import java.util.HashMap;

import tech.mobi.child.base.BaseAct;
import tech.mobi.child.bean.PictureBean;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.assist.FailReason;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class CZDAClientDetailPicAct extends BaseAct implements OnClickListener {

	private TextView tvProName;
	public static TextView tvPager;
	public static TextView tvDesc;
	private ArrayList<View> pageViews;
	private ViewGroup main;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private static final String STATE_POSITION = "STATE_POSITION";
	DisplayImageOptions options;
	ViewPager viewPager;
	// // 包裹小圆点的LinearLayout
	// private ViewGroup group;
	// private ImageView[] imageViews;
	// private ImageView imageView;
	private Bundle savedInstanceState;

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, viewPager.getCurrentItem());
	}

	private String strId = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.czda_client_list_detail_img_main);
		this.savedInstanceState = savedInstanceState;
		// ivBack = (ImageView) this.findViewById(R.id.ivBack);
		tvProName = (TextView) this.findViewById(R.id.tvProName);
		tvPager = (TextView) this.findViewById(R.id.tvPager);
		tvDesc = (TextView) this.findViewById(R.id.tvDesc);

//		Intent intent = this.getIntent();
//		if (intent != null && intent.getStringExtra("pro_name") != null) {
//			tvProName.setText(intent.getStringExtra("pro_name"));
//		}
//		if (intent != null && intent.getStringExtra("id") != null) {
//			strId = intent.getStringExtra("id");
//		}
//
//		if (strId != null && !"".equals(strId)) {
//		
//			getDataList(strId);
//		}
		
		
		
		 
		Bundle bundle = getIntent().getExtras();
		String[] imageUrls = bundle.getStringArray("Images");
		int pagerPosition = bundle.getInt("ImagesPosition", 0);

		if (savedInstanceState != null) {
			pagerPosition = savedInstanceState.getInt(STATE_POSITION);
		}
		
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext())
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.discCacheFileCount(60)// Set max cache file count in SD card
				.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging() // Not
																				// necessary
																				// in
																				// common
				.build();

		// Initialize ImageLoader with configuration
		ImageLoader.getInstance().init(config);

		options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.desklogo)
		.showImageOnFail(R.drawable.desklogo)
		.resetViewBeforeLoading(true).cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.displayer(new FadeInBitmapDisplayer(300)).build();

		viewPager = (ViewPager) findViewById(R.id.myviewpager);
		viewPager.setAdapter(new ImagePagerAdapter(imageUrls));
		viewPager
				.setOnPageChangeListener(new GuidePageChangeListener(imageUrls));
		viewPager.setCurrentItem(pagerPosition);

	}

	
//	private void getDataList(String id) {
//		HashMap<String, String> map = new HashMap<String, String>();
//		map.put(MainAct.USER_NAME, User.userName);
//		map.put("releaseId", id + "");
//		map.put("clientVersion", getClientVersionNumber());
//		Task task = new Task(TaskType.TASK_GOOD_CLIENT_PIC_LIST_INFO, map);
//		MainService.newTask(task);
//	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivBack:
			this.finish();
			break;
		}

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {
		int type = (Integer) param[0];
//		switch (type) {
//		case TaskType.TASK_GOOD_CLIENT_PIC_LIST_INFO:
//			try {
//				HashMap<String, Object> map = (HashMap<String, Object>) param[1];
//				if (map.size() == 1) {
//					ArrayList<PictureBean> data = (ArrayList<PictureBean>) map
//							.get("data");
//					if (data.size() > 0) {
//						bindDatas(data);
//					}
//				}
//			} catch (Exception e) {
//				this.finish();
//			}
//			break;
//		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private class ImagePagerAdapter extends PagerAdapter {

		private String[] imageUrls;
		private LayoutInflater inflater;

		ImagePagerAdapter(String[] imageUrls) {
			this.imageUrls = imageUrls;
			inflater = getLayoutInflater();
			CZDAClientDetailPicAct.tvPager.setText("1/" + imageUrls.length);
//			CZDAClientDetailPicAct.tvDesc.setText(pathBean.get(0).getPicdes());
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return imageUrls.length;
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			View imageLayout = inflater.inflate(
					R.layout.czda_client_list_detail_img_items, view, false);
			ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);
			final ProgressBar progressBar = (ProgressBar) imageLayout
					.findViewById(R.id.loading);

			imageLoader.displayImage(imageUrls[position],
					imageView, options, new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							progressBar.setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							String message = null;
							switch (failReason.getType()) {
							case IO_ERROR:
								message = "网络链接失败";
								// message = "Input/Output error";
								break;
							case DECODING_ERROR:
								message = "图片不能被解析";
								// message = "Image can't be decoded";
								break;
							case NETWORK_DENIED:
								message = "下载被拒绝";
								// message = "Downloads are denied";
								break;
							case OUT_OF_MEMORY:
								message = "内存不足";
								// message = "Out Of Memory error";
								break;
							case UNKNOWN:
								message = "未知错误";
								// message = "Unknown error";
								break;
							}
							Toast.makeText(CZDAClientDetailPicAct.this,
									message, Toast.LENGTH_SHORT).show();

							progressBar.setVisibility(View.GONE);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							progressBar.setVisibility(View.GONE);
						}
					});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}

	}

	// 指引页面更改事件监听器
	class GuidePageChangeListener implements OnPageChangeListener {

		private String[] imageUrls;
		private LayoutInflater inflater;

		GuidePageChangeListener(String[] imageUrls) {
			this.imageUrls = imageUrls;
			inflater = getLayoutInflater();
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageSelected(int arg0) {
			CZDAClientDetailPicAct.tvPager.setText((arg0 + 1) + "/"
					+ imageUrls.length);
//			CZDAClientDetailPicAct.tvDesc.setText(pathBean.get(arg0)
//					.getPicdes());
			// for (int i = 0; i < pathBean.size(); i++) {
			// imageViews[arg0].setBackgroundResource(R.drawable.help_flag_focused_n);
			// if (arg0 != i) {
			// imageViews[i].setBackgroundResource(R.drawable.help_flag_n);
			// }
			// }
		}
	}

}
